from tkinter import scrolledtext
from tkinter import filedialog
import tkinter as tk
import tkinter.ttk
import Esa_DownLoader
import datetime
import calendar
import threading
import logging
import ctypes
import inspect
import signal
import time
import sys
import os


class LoggerBox(scrolledtext.ScrolledText):

    def write(self, message):
        self.insert("end", message)

def _async_raise(tid, exctype):
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):
    print(f'\nt -> {thread}')
    print(f'\nthread.ident -> {thread.ident}')
    _async_raise(thread.ident, SystemExit)
    thread.join()

# ui
class ui:

    width, height = 800, 880
    line_height = 50
    log=logging.getLogger('log1')
    log.setLevel(logging.DEBUG)
    exit_event = threading.Event()

    def __init__(self):

        # 定义窗口
        self.get_window()
        self.config_path = tk.StringVar()
        self.link_folder = tk.StringVar()
        self.zip_folder = tk.StringVar()
        self.link_folder.set(r"Z:\ProvinceZip")
        self.zip_folder.set(r"Z:\Sentinel2L1cZip")
        self.tiles_str = tk.StringVar()
        line_iter = iter(range(50))
        self.sentinel_frame(next(line_iter))
        self.province_frame(next(line_iter))
        self.period_frame(next(line_iter))
        self.thread_frame(next(line_iter))
        self.cloud_frame(next(line_iter))
        self.sleep_frame(next(line_iter))
        self.acount_frame(next(line_iter))
        self.zip_folder_frame(next(line_iter))
        self.link_folder_frame(next(line_iter))
        # self.send_data_frame(next(line_iter))
        self.task_button_frame(next(line_iter))
        self.progressbar_frame(next(line_iter))
        self.print_running_frame(next(line_iter))
        self.window.mainloop()

    def get_window(self):
        self.window = tk.Tk()
        self.window.title('Sentinel-2 By ESA')
        screenwidth = self.window.winfo_screenwidth() # 屏幕宽度
        screenheight = self.window.winfo_screenheight() # 屏幕高度
        x = int((screenwidth - self.width) / 2)
        y = int((screenheight - self.height) / 2)
        locat = f"{self.width}x{self.height}+{x}+{y}"
        self.window.geometry(locat) # 大小以及位置
        self.window.resizable(0,0) 
        return

    def sentinel_frame(self, row):
        frame=tkinter.ttk.Frame(self.window,width=self.width)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))

        tk.Label(
            frame,text="图幅列表",font=('宋体','14','bold'),height=3,
        ).grid(column=next(column_iter),row=0,sticky=tk.W+tk.E)

        frame2 = tkinter.ttk.Frame(frame)
        frame2.grid(column=1,row=0,sticky=tk.W+tk.E)

        self.tilestr_entry=tk.Entry(
            frame2,
            width=63,
            background = 'white',
            borderwidth = 3,
            relief = 'sunken',
            insertwidth = 3,
            font = ('Helvetica', '14', 'bold'),
            textvariable=self.tiles_str,
            selectforeground = 'red',
            selectbackground = 'blue',
            selectborderwidth = 3,
            show=None)
        self.tilestr_entry.pack(side=tk.TOP,fill=tk.NONE) 

        scroll = tk.Scrollbar(
            frame2,
            orient=tk.HORIZONTAL,
            cursor="arrow",
            command=self.tilestr_entry.xview,
            # width=85
        )
        scroll.pack(side=tk.BOTTOM,fill=tk.X, padx=0)
        self.tilestr_entry.config(xscrollcommand=scroll.set)

        return

    def province_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))
        tk.Label(
            frame,text="选择省份",font=('宋体','14','bold'),height=3,
        ).grid(column=next(column_iter),row=0,sticky=tk.W+tk.E)

        provinces = list(Esa_DownLoader.china_tiles.keys())
        self.province_combobox=tkinter.ttk.Combobox(
            frame,
            # width=6,
            height=len(provinces),
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="请选择省份（非必须）",
            font = ('', '12', ''),
            values=provinces,
            show=None
        )
        self.province_combobox.grid(column=next(column_iter),row=0,sticky='we')
        self.province_combobox.current(0)

        self.province_combobox.bind(
            '<<ComboboxSelected>>', 
            lambda event: (
                self.tiles_str.set("-".join(Esa_DownLoader.china_tiles[self.province_combobox.get()])),
                self.scrolled_text.delete(0.0, tkinter.END),
                self.window.update(),
                self.update_info("-".join(Esa_DownLoader.china_tiles[self.province_combobox.get()]))	
            )
        )
        return

    def period_frame(self,row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))

        tk.Label(
            frame,text="开始时间",font=('宋体','14','bold'),height=3,
        ).grid(column=next(column_iter),row=0,sticky=tk.W+tk.E)
        
        self.start_date(frame,column_iter)

        tk.Label(
            frame,text="结束时间",font=('宋体','14','bold'),height=3,
        ).grid(column=next(column_iter),row=0,sticky='we')

        self.end_date(frame, column_iter)
        return

    def start_date(self, frame, column_iter):
        self.start_year=tkinter.ttk.Combobox(
            frame,
            width=4,
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",  # 必须为空
            font = ('', '12', ''),
            values=tuple(range(datetime.datetime.now().year,2016,-1)),
            show=None
        )
        self.start_year.current(0)
        self.start_year.grid(column=next(column_iter),row=0,sticky='we')
        self.start_month=tkinter.ttk.Combobox(
            frame,
            width=2,
            height=12,
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=tuple(range(1,13)),
            show=None
        )
        self.start_month.current(0)
        self.start_month.grid(column=next(column_iter),row=0,sticky='we')

        self.start_month.bind(
            '<<ComboboxSelected>>', 
            lambda event: (
                self.start_day.config(
                    {"values":tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.start_year.get()), 
                                    int(self.start_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.start_day.config(
                    {
                        "values": tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.start_year.get()), 
                                    int(self.start_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.start_day.config(
                    {
                        "height": calendar.monthrange(
                                    int(self.start_year.get()), 
                                    int(self.start_month.get())
                                )[1]		
                    }
                ),
                self.start_day.current(0)
            )
        )
        self.start_year.bind(
            '<<ComboboxSelected>>', 
            lambda event: (
                self.start_day.config(
                    {"values":tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.start_year.get()), 
                                    int(self.start_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.start_day.config(
                    {
                        "values": tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.start_year.get()), 
                                    int(self.start_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.start_day.config(
                    {
                        "height": calendar.monthrange(
                                    int(self.start_year.get()), 
                                    int(self.start_month.get())
                                )[1]		
                    }
                ),
                self.start_day.current(0)
            )
        )

        self.start_day=tkinter.ttk.Combobox(
            frame,
            width=2,
            # height=day_count,
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            # values=days,
            show=None
        )
        self.start_day.grid(column=next(column_iter),row=0,sticky='we')
        return

    def end_date(self,frame, column_iter):
        self.end_year=tkinter.ttk.Combobox(
            frame,
            width=4,
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=tuple(range(datetime.datetime.now().year,2016,-1)),
            show=None
        )
        self.end_year.current(0)
        self.end_year.grid(column=next(column_iter),row=0,sticky='we')
        self.end_month=tkinter.ttk.Combobox(
            frame,
            width=2,
            height=12,
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=tuple(range(1,13)),
            show=None
        )
        self.end_month.current(0)
        self.end_month.grid(column=next(column_iter),row=0,sticky='we')

        self.end_month.bind(
            '<<ComboboxSelected>>', 
            lambda event: (
                self.end_day.config(
                    {"values":tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.end_day.config(
                    {
                        "values": tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.end_day.config(
                    {
                        "height": calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]
                    }
                ),
                self.end_day.current(calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]-1
                )
            )
        )
        self.end_year.bind(
            '<<ComboboxSelected>>', 
            lambda event: (
                self.end_day.config(
                    {"values":tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.end_day.config(
                    {
                        "values": tuple(
                            range(
                                1,
                                calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]+1
                            )
                        )
                    }
                ),
                self.end_day.config(
                    {
                        "height": calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]
                    }
                ),
                self.end_day.current(calendar.monthrange(
                                    int(self.end_year.get()), 
                                    int(self.end_month.get())
                                )[1]-1
                )
            )
        )

        self.end_day=tkinter.ttk.Combobox(
            frame,
            width=2,
            # height=day_count,
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            # values=days,
            show=None
        )
        self.end_day.grid(column=next(column_iter),row=0,sticky='we')
        return

    def thread_frame(self,row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text=f"线程数量",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        max_thread = tk.IntVar()
        max_thread.set(1)
        self.thread_scale=tk.Scale(
            frame, 
            # label="MaxCloud",    # 标签
            variable=max_thread, 	# 值
            from_=1,    #  最小值， 记住是from_， from是关键字
            to=4,       #  最大值
            resolution=1,  # 步进值
            show=True,   # 是否在上面显示值
            orient=tk.HORIZONTAL,  # 水平显示
            length=680,  # 滑块长度
            # command=lambda value, key=k:self.get_value(value, key)
        )
        self.thread_scale.grid(column=1,row=0,sticky='we')
        return

    def cloud_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text=f"最大云量",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        max_clound = tk.IntVar()
        max_clound.set(100)
        self.maxcloud_scale=tk.Scale(
            frame, 
            # label="MaxCloud",    # 标签
            variable=max_clound, 	# 值
            from_=0,    #  最小值， 记住是from_， from是关键字
            to=100,       #  最大值
            resolution=1,  # 步进值
            show=True,   # 是否在上面显示值
            orient=tk.HORIZONTAL,  # 水平显示
            length=680,  # 滑块长度
            # command=lambda value, key=k:self.get_value(value, key)
        )
        self.maxcloud_scale.grid(column=1,row=0,sticky='we')
        return

    def sleep_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text=f"间隔时长",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        sleep = tk.IntVar()
        sleep.set(15)
        self.sleep_scale=tk.Scale(
            frame, 
            # label="MaxCloud",    # 标签
            variable=sleep, 	# 值
            from_=0,    #  最小值， 记住是from_， from是关键字
            to=120,       #  最大值
            resolution=1,  # 步进值
            show=True,   # 是否在上面显示值
            orient=tk.HORIZONTAL,  # 水平显示
            length=680,  # 滑块长度
            # command=lambda value, key=k:self.get_value(value, key)
        )
        self.sleep_scale.grid(column=1,row=0,sticky='we')
        return

    def acount_frame(self, row):
        frame=tkinter.ttk.Frame(self.window,width=self.width)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))
        tk.Label(
            frame,text="选择账户",font=('宋体','14','bold'),height=3,
        ).grid(column=next(column_iter),row=0,sticky=tk.W+tk.E)

        usernames = list(Esa_DownLoader.account_infos.keys())
        self.username=tkinter.ttk.Combobox(
            frame,
            # width=4,
            height=len(usernames),
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",  # 必须为空
            font = ('', '12', ''),
            values=tuple(usernames),
            show=None
        )
        self.username.current(0)
        self.username.grid(column=next(column_iter),row=0,sticky='we')
        return

    def config_frame(self, row):
        frame=tkinter.ttk.Frame(self.window,width=self.width)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))

        tk.Label(
            frame,text="配置文件",font=('宋体','14','bold'),height=3,
            ).grid(column=next(column_iter),row=0,sticky='we')
        self.jsonfile_entry=tk.Entry(
            frame,
            width=74,
            background = 'white',
            borderwidth = 3,
            relief = 'sunken',
            insertwidth = 3,
            font = ('宋体', '12', ''),
            textvariable=self.config_path,
            selectforeground = 'red',
            selectbackground = 'blue',
            selectborderwidth = 0,
            show=None, 
        )
        self.jsonfile_entry.grid(column=next(column_iter),row=0,sticky='we')
        self.select_file_button=tk.Button(
            frame,
            text="选择文件",
            font=('','14','bold'), 
            bg="#50b7c1",
            command=lambda:
                self.config_path.set(
                    filedialog.askopenfilename(filetypes=[("配置文件", [".txt",])])
                )
        ) 
        self.select_file_button.grid(column=next(column_iter),row=0,sticky='we')
        return

    def link_folder_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))
        tk.Label(
            frame,text="映射目录",font=('宋体','14','bold'),height=3
        ).grid(column=next(column_iter),row=0,sticky='we') 
        self.link_dir=tk.Entry(
            frame,
            width=74,
            background = 'white',
            borderwidth = 3,
            relief = 'sunken',
            insertwidth = 3,
            font = ('宋体', '12', ''),
            textvariable=self.link_folder,
            selectforeground = 'red',
            selectbackground = 'blue',
            selectborderwidth = 0,
            show=None, 
        )  
        self.link_dir.grid(column=next(column_iter),row=0,sticky='we')
        tk.Button(
            frame,
            text="选择目录",
            font=('','14','bold'), 
            bg="#50b7c1",
            command=lambda: self.link_folder.set(filedialog.askdirectory().replace('/','\\')),
        ).grid(column=next(column_iter),row=0,sticky='we')
        return

    def zip_folder_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))
        tk.Label(
            frame,text="远程目录",font=('宋体','14','bold'),height=3
        ).grid(column=next(column_iter),row=0,sticky='we') 
        self.local_dir=tk.Entry(
            frame,
            width=74,
            background = 'white',
            borderwidth = 3,
            relief = 'sunken',
            insertwidth = 3,
            font = ('宋体', '12', ''),
            textvariable=self.zip_folder,
            selectforeground = 'red',
            selectbackground = 'blue',
            selectborderwidth = 0,
            show=None, 
        )  
        self.local_dir.grid(column=next(column_iter),row=0,sticky='we')
        tk.Button(
            frame,
            text="选择目录",
            font=('','14','bold'), 
            bg="#50b7c1",
            command=lambda: self.zip_folder.set(filedialog.askdirectory().replace('/','\\')),
        ).grid(column=next(column_iter),row=0,sticky='we')
        return

    def send_data_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))

        tk.Label(
            frame,text="是否Link：",font=('宋体','14','bold'),height=3
        ).grid(column=next(column_iter),row=0,sticky='we') 

        self.send_flag = tk.IntVar()
        self.send_flag.set(1)
        tk.Checkbutton(
            frame,
            text="（非省份）",
            variable=self.send_flag,
        ).grid(column=next(column_iter),row=0,sticky='we')  
        # self.checkbutton_1
        # self.checkbutton_1.select()
        print()
        return

    def task_button_frame(self, row):
        frame=tkinter.ttk.Frame(self.window,width=self.width,height=60)
        frame.place(x=0,y=self.line_height*row)

        self.start_button=tk.Button(
            frame,
            text="开始下载",
            font=('','14','bold'),
            bg="#50b7c1",
            activebackground="red",
            activeforeground="blue",
            command=lambda: self.set_thread(self.run_main),
        )
        self.start_button.place(relx=0.33,rely=0.5,anchor='center')

        self.pause_button=tk.Button(
            frame,
            text="暂停任务",
            font=('','14','bold'),
            bg="#50b7c1",
            activebackground="red",
            activeforeground="blue",
            command=lambda: self.stop_thread(),
            state='disabled',
        )
        self.pause_button.place(relx=0.66,rely=0.5,anchor='center')
        return

    def progressbar_frame(self,row):
        frame=tkinter.ttk.Frame(self.window,width=self.width)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(10))

        tk.Label(
            frame,text="运行进度",font=('宋体','14','bold'),height=3,
        ).grid(column=next(column_iter),row=0,sticky='we')  

        self.progressbar = tkinter.ttk.Progressbar(
            frame,
            length=690,
            # maximum=100,
            value=0,
            cursor='spider',
            # mode="determinate",
            mode="indeterminate",
            orient=tk.HORIZONTAL,
        )
        self.progressbar.grid(column=next(column_iter),row=0,sticky='we')    
        return

    def print_running_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        column_iter = iter(range(5))
        tk.Label(
            frame,text="运行信息",font=('宋体','14','bold'),
        ).grid(column=next(column_iter),row=0,sticky='we')
        self.scrolled_text = LoggerBox(
            frame, 
            state='normal',
            wrap = tk.WORD,
            # font=('Times New Roman', 12),
            font="TkFixedFont",
            width=98, 
            height=24,
        )

        # self.scrolled_text = scrolledtext.ScrolledText(
        #     frame, 
        #     state='normal',
        #     wrap = tk.WORD,
        #     # font=('Times New Roman', 12),
        #     font="TkFixedFont",
        #     width=98, 
        #     height=24,
        # ) 
        self.scrolled_text.tag_config('INFO', foreground='black')
        self.scrolled_text.tag_config('DEBUG', foreground='gray')
        self.scrolled_text.tag_config('WARNING', foreground='orange')
        self.scrolled_text.tag_config('ERROR', foreground='red')
        self.scrolled_text.tag_config('CRITICAL', foreground='red', underline=1)
        self.scrolled_text.grid(column=next(column_iter),row=0,rowspan=20,sticky='we')
        # self.scrolled_text.pack(side=tk.LEFT,fill=tk.NONE) 

        handler = logging.StreamHandler(self.scrolled_text)
        self.log.addHandler(handler)
        return

    def set_thread(self,func,*args):
        self.thread = threading.Thread(target=func,args=args,daemon=True)
        self.thread.start()
        return

    def stop_thread(self):
        
        self.progressbar.stop()
        self.exit_event.set()
        tk.messagebox.showinfo('Message', f'终止下载！')
        self.start_button.config({"state":tk.NORMAL})
        self.pause_button.config({"state":tk.DISABLED})
            # self.thread.join(timeout=0.1)

            # time.sleep(5)
            # print(self.thread.is_alive())
            # stop_thread(self.thread)
            # self.thread.stop()
            # time.sleep(5)
            # print(self.thread.is_alive())
            # sys.exit(0)
        return

    def update_info(self,string):
        datetime_str = datetime.datetime.now().strftime('%H:%M:%S')
        string = f"{datetime_str}>{string}"
        self.log.info(string)
        # self.scrolled_text.insert(tk.END, string)
        self.scrolled_text.see(tk.END)
        self.scrolled_text.focus()
        self.window.update()
        return

    def _end(self,flag,e_info,c_info=None):
        if flag:
            self.progressbar.stop()
            self.start_button.config({"state":tk.NORMAL})
            self.pause_button.config({"state":tk.DISABLED})
            tk.messagebox.showwarning('Waring', e_info)
        else:
            self.update_info(c_info)  if c_info else None
        return

    def run_main(self):
        self.start_button.config({"state":tk.DISABLED})
        self.pause_button.config({"state":tk.NORMAL})
        self.progressbar.start()
        self.scrolled_text.configure(state='normal')
        self.scrolled_text.delete(0.0, tkinter.END)
        self.window.update()

        tiles_str = self.tilestr_entry.get()
        self._end(
            tiles_str=='',
            "未选择下载图幅!",
            f"下载图幅：{tiles_str}"
        ) 

        tiles = [tile.upper() for tile in tiles_str.split("-")]
        
        self._end(
            (self.start_day.get()=='')or(self.end_day.get()==''),
            "未选择下载日期!",
        )
        start_date = datetime.date(
                int(self.start_year.get()), 
                int(self.start_month.get()), 
                int(self.start_day.get())
                ).strftime('%Y-%m-%d')
        self.update_info(f"开始日期：{start_date}")
        end_date = datetime.date(
                int(self.end_year.get()), 
                int(self.end_month.get()),
                int(self.end_day.get())
                ).strftime('%Y-%m-%d')
        self.update_info(f"结束日期：{end_date}")
       
        thread_sum = self.thread_scale.get()
        max_cloud = self.maxcloud_scale.get()
        sleep = self.sleep_scale.get()
        self.update_info(f"最大线程量：{thread_sum}个")
        self.update_info(f"最大含云量：{max_cloud}%")
        self.update_info(f"下载间隔时长：{sleep}s")

        self._end(
            self.username.get()=="请选择ESA账号",
            "未选择ESA账号!",
            f"ESA账户信息:{self.username.get()}"
        )
        username = self.username.get()
        password = Esa_DownLoader.account_infos[username]
        
        local_dir = self.local_dir.get()
        self._end(
            local_dir == "",
            "未选择挂载目录！",
            f"挂载目录：{local_dir}"
        )

        link_dir = self.link_dir.get()
        self._end(
            link_dir == "",
            "未选择链接目录！",
            f"链接目录：{link_dir}"
        )

        province = self.province_combobox.get()
        province = province if province != "请选择省份（非必须）" else None

        Esa_DownLoader.main(
            tiles,
            start_date,
            end_date,
            max_cloud,
            username,
            password,
            local_dir,
            thread_sum,
            sleep,
            province,
            link_dir
        )

        # args = (
        #     tiles,
        #     start_date,
        #     end_date,
        #     max_cloud,
        #     username,
        #     password,
        #     local_dir,
        #     thread_sum,
        #     sleep,
        #     province,
        #     link_dir
        # )

        # thread = threading.Thread(target=Esa_DownLoader.main,args=args)
        # thread.start()

        # print(thread.is_alive)
        # print(self.exit_event)

        # while thread.is_alive:
        #     if self.exit_event:
        #         sys.exit(0)
        #     else:
        #         time.sleep(1)
        #         print(0)

        self.progressbar.stop()
        tk.messagebox.showinfo('Message', f'下载完成！')
        self.start_button.config({"state":tk.NORMAL})
        self.pause_button.config({"state":tk.DISABLED})
        return


if __name__=="__main__":
    ui()